package com.ht.searchrooky.client.gui.service;

import javax.jms.Connection;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;

import com.ht.searchrooky.request.Request;



public class SampleClient
{
    Context ctx;
    Connection conn;
   // Session session;
    Queue mq;
    //MessageProducer mp;
 
    public SampleClient()
    {
	super();
	try
	{
	    init();
	}
	catch (Exception e)
	{
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	// TODO Auto-generated constructor stub
    }
    public void init() throws Exception{
	InitialContext icx=new InitialContext();
	 ctx = new javax.naming.InitialContext();
	// lookup the connection factory
	//System.out.println(11);
	javax.jms.ConnectionFactory factory = (javax.jms.ConnectionFactory)ctx.lookup("ConnectionFactory");
	// create a new TopicConnection for pub/sub messaging
	 conn = factory.createConnection();
	// Session session =conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
	//System.out.println(session.getAcknowledgeMode());
	 mq=(Queue)ctx.lookup("RequestQueue");
	//System.out.println("queue"+mq);
	// mp=session.createProducer(mq);

	//conn.start();
//	TextMessage tm;
//	for (int i = 0; i < 10; i++) {
//		tm=session.createTextMessage("ss"+i);
//		mp.send(tm);
//		System.out.println(i+"==");
//		//Thread.sleep(1000);
//	}
//	conn.close();
    }
    public Request  send (Request req){
	System.out.println(" send ....."+req);
	Request request=null;
	try
	{
	    conn.start();
	    Session session =conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
	    ObjectMessage msg=session.createObjectMessage();
	    msg.setObject(req);
	    Queue replyto=(Queue) ctx.lookup("ResponseToClientAQueue");
	    msg.setJMSReplyTo(replyto);
	    MessageProducer mp=session.createProducer(mq);
	    mp.send(msg);
	    
	    
	    MessageConsumer consumer= session.createConsumer(replyto);
	    request = (Request)((ObjectMessage)(consumer.receive())).getObject();
	    System.out.println("get response from server "+request);
	    session.close();
	    //conn.close();
	    System.out.println("receive response  "+request);
	    return request;
	    
	    
	}
	catch (Exception e)
	{
	  
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	
	return request;
	
    }
    
    
    
}
